"""
图片处理API蓝图
提供水印去除、GIF创建等功能
"""

from flask import Blueprint, request, jsonify, send_file, current_app
import os
import logging
from app.service.image_service import ImageService
from app.tools.utils import get_safe_filename, validate_file_extension

# 创建图片API蓝图
image_bp = Blueprint('image', __name__, url_prefix='/image')

def allowed_file(filename, allowed_extensions):
    """检查文件格式是否允许"""
    return validate_file_extension(filename, allowed_extensions)

def get_image_service():
    """获取图片服务实例"""
    return ImageService(current_app.config['UPLOAD_FOLDER'], current_app.config['OUTPUT_FOLDER'])

@image_bp.route('/remove_watermark', methods=['POST'])
def remove_watermark():
    """去除视频水印"""
    try:
        if 'video' not in request.files:
            return jsonify({'error': '没有上传视频文件'}), 400
        
        file = request.files['video']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        if not allowed_file(file.filename, current_app.config['ALLOWED_EXTENSIONS']):
            return jsonify({'error': '不支持的文件格式'}), 400
        
        # 获取水印区域参数
        x = request.form.get('x', type=int)
        y = request.form.get('y', type=int)
        width = request.form.get('width', type=int)
        height = request.form.get('height', type=int)
        
        if not all([x is not None, y is not None, width is not None, height is not None]):
            return jsonify({'error': '需要提供水印区域参数: x, y, width, height'}), 400
        
        # 保存上传的文件
        filename = get_safe_filename(file.filename)
        temp_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        file.save(temp_path)
        
        # 去除水印
        image_service = get_image_service()
        result = image_service.remove_watermark_service(temp_path, x, y, width, height)
        if not result['success']:
            return jsonify({'error': result['error']}), 500
        
        output_path = result['output_path']
        
        # 清理临时文件
        os.remove(temp_path)
        
        return send_file(output_path, as_attachment=True, download_name='video_no_watermark.mp4')
    
    except Exception as e:
        logging.error(f"去除水印失败: {e}")
        return jsonify({'error': str(e)}), 500

@image_bp.route('/create_gif', methods=['POST'])
def create_gif():
    """从视频创建GIF"""
    try:
        if 'video' not in request.files:
            return jsonify({'error': '没有上传视频文件'}), 400
        
        file = request.files['video']
        duration = int(request.form.get('duration', 10))
        fps = int(request.form.get('fps', 10))
        
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        if not allowed_file(file.filename, current_app.config['ALLOWED_EXTENSIONS']):
            return jsonify({'error': '不支持的文件格式'}), 400
        
        # 保存上传的文件
        filename = get_safe_filename(file.filename)
        temp_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        file.save(temp_path)
        
        # 创建GIF
        image_service = get_image_service()
        result = image_service.create_gif_service(temp_path, duration, fps)
        if not result['success']:
            return jsonify({'error': result['error']}), 500
        
        output_path = result['output_path']
        
        # 清理临时文件
        os.remove(temp_path)
        
        return send_file(output_path, as_attachment=True, download_name='video_gif.gif')
    
    except Exception as e:
        logging.error(f"创建GIF失败: {e}")
        return jsonify({'error': str(e)}), 500 